package io.renren.modules.app.message.handler;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.ObjectUtil;
import io.renren.common.utils.EnvironmentHelper;
import io.renren.modules.app.message.dto.JdVopMessageReadEvent;
import io.renren.modules.app.message.dto.ProductUpdateEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author :
 * @version V1.0
 * @Project:
 * @Package
 * @Description: 事件监听器
 * @date
 **/
@Component
@Slf4j
public  class JdVopEventListener {

//    @Autowired
//    private JdVopApiHandler jdVopApiHandler;
//    @Autowired
//    private ISmsHomeRecommendProductService smsHomeRecommendProductService;

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private EnvironmentHelper environmentHelper;

    private ThreadPoolExecutor executor= new ThreadPoolExecutor(2,10, 20, TimeUnit.MILLISECONDS,new LinkedBlockingDeque<>(1000));

    @PostConstruct
    public void setProperties(){
        executor.allowCoreThreadTimeOut(true);
    }
    @EventListener
    public void handleMessageDelEvent(JdVopMessageReadEvent event){
        ThreadUtil.execAsync(()-> {
            boolean flag=event.isFlag();
            long msgId=event.getMsgId();
            String type=event.getType();
            log.info("type={}",type);
            JdVopMessageHandler messageHandler=applicationContext.getBean(type,JdVopMessageHandler.class);
            int index=messageHandler.decrement();//剩余个数-1
            if(flag){
                boolean isProd=environmentHelper.isProd();
                if(isProd){//商用环境在处理
//                    jdVopApiHandler.delMessages(msgId);
                }else{
                    log.info("模拟 JD_VOP MSG={} DEL SUCCESS",msgId);
                }
            }
            log.info("DEL_JD_VOP {} [ID={}],{}",index,msgId,flag?"已成功处理":"未成功处理");
        });
    }

    /**
     * 处理商品更新事件
     * @param event
     */
    @EventListener
    public void handleProductUpdateEvent(ProductUpdateEvent event){
       Long productId= event.getPid();
       if(ObjectUtil.isNotNull(productId) && productId>0){
           log.info("商品[{}]下架，删除推荐区商品",productId);
//           executor.execute(()-> this.smsHomeRecommendProductService.removeProduct(productId));
       }
    }
}
